<?php
//   +----------------------------------------------------------------------
//   | Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved.
//   | Licensed ( http://www.hdphp.cn/licenses/ )
//   | Author: Jack <sophia2152@qq.com>
//   | 官方网址: http://www.hdphp.cn
//   | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//   | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//   +----------------------------------------------------------------------
namespace app\controller\admin;

use app\Request;
use app\services\other\CacheServices;
use app\services\system\attachment\SystemAttachmentServices;
use hdphp\services\CacheService;
use think\captcha\facade\Captcha;
use think\Response;

/**
 * Class：公共接口
 * 创建人：Jack
 * 创建时间：2023/11/22 10:57
 * @package app\controller\admin
 */
class PublicController
{

    /**
     * 注释：验证码
     * 创建人：Jack
     * 创建时间：2023/11/22 15:48
     * @return Response
     */
    public function identifyingCode()
    {
        return Captcha::create();
    }

    /**
     * 注释：下载文件
     * 创建人：Jack
     * 创建时间：2023/11/22 15:45
     * @param string $key
     * @return Response|\think\response\File
     */
    public function download(string $key = '')
    {
        if (!$key) {
            return Response::create()->code(500);
        }
        $fileName = CacheService::get($key);
        if (is_array($fileName) && isset($fileName['path']) && isset($fileName['fileName']) && $fileName['path'] && $fileName['fileName'] && file_exists($fileName['path'])) {
            CacheService::delete($key);
            return download($fileName['path'], $fileName['fileName']);
        }

        return Response::create()->code(500);
    }

    /**
     * 注释：扫码上传
     * 创建人：Jack
     * 创建时间：2023/11/22 15:45
     * @param Request $request
     * @return mixed
     */
    public function scanUpload(Request $request)
    {
        [$file, $upload_type, $cache, $uploadToken, $type, $relation_id, $pid] = $request->postMore([
            ['file', 'file'],
            ['upload_type', 0],
            ['cache', ''],
            ['uploadToken', ''],
            ['type', 0],
            ['relation_id', 0],
            ['pid', 0]
        ], true);
        if (!$cache || !$uploadToken) {
            return app('json')->fail('参数有误，无法上传!');
        }
        $cacheServices = app()->make(CacheServices::class);
        $service = app()->make(SystemAttachmentServices::class);
        if ($cacheServices->getDbCache($cache, '') == '' || $cacheServices->getDbCache($cache, '') != $uploadToken) {
            return app('json')->fail('请重新扫码上传!');
        }
        $service->storeUpload((int)$pid, $file, $relation_id, $type, $upload_type, $uploadToken);
        return app('json')->success('上传成功!');
    }

}